<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="请输入要BB的内容（最多吐槽120字）" maxlength="120" v-model="msg"></textarea>
    <mt-button  type="primary" size="large" @click="postComment">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item, index) in comments" :key="item.user_name">
        <div
          class="cmt-title"
        >第{{index +1}}楼&nbsp;&nbsp;&nbsp;&nbsp;用户:{{item.user_name}}&nbsp;&nbsp;&nbsp;&nbsp;发表时间:{{item.add_time}}</div>
        <div class="cmt-body">{{item.content?item.content:'此用户太懒，什么也没有留下...'}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>
<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      pageIndex: 1,
      comments: [],
      msg: ""
    };
  },
  props: ["id"],
  created() {
    this.getComments();
  },
  methods: {
    getComments() {
      this.$http.get("../../../static/commentlist.json").then(result => {
        let response = result.body.data.message;
        let total = this.pageIndex * 2;
        if (response.length < total) {
          Toast({
            message: "我也是有底线的哦...",
            position: "bottom",
            duration: 3000,
            iconClass: "glyphicon glyphicon-ban-circle",
            className: "myicon"
          });
          this.comments = response;
        } else {
          response.forEach((val, index, val_arr) => {
            if (total > 0) {
              this.comments.push(val);
              total--;
            }
          });
        }
      });
    },
    getMore() {
      this.comments = [];
      this.pageIndex++;
      this.getComments();
    },
    postComment() {
      if (!this.msg) {
        Toast({
          message: "请输入您想吐槽地内容!",
          position: "middle",
          duration: 3000,
          iconClass: "glyphicon glyphicon-pencil",
          className: "myicon"
        });
        return;
      } else {
        this.comments.unshift({
          user_name: "匿名用户" + Math.ceil(Math.random() * 10),
          add_time: new Date().toLocaleString(),
          content: this.msg
        });
        Toast({
          message: "评论成功!",
          position: "middle",
          duration: 3000,
          iconClass: "glyphicon glyphicon-ban-circle",
          className: "myicon"
        });
        this.msg = "";
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 16px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }

  .cmt-list {
    margin: 5px 0;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        line-height: 30px;
        background-color: #ccc;
      }
      .cmt-body {
        line-height: 35px;
        text-indent: 2em;
      }
    }
  }
}
</style>